package com.ydd.controller.user;

import com.ydd.constant.JwtClaimsConstant;
import com.ydd.dto.YddUserLoginDTO;
import com.ydd.entity.YddUser;
import com.ydd.properties.JwtProperties;
import com.ydd.result.Result;
import com.ydd.service.IYddUserService;
import com.ydd.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description TODO
 * @Author itbobo
 * @Date 2023-06-01 22:03
 */
@Api(tags = "用户端登录相关接口")
@Slf4j
@RestController
@RequestMapping("/api/home/index")
public class UserLoginController {

    @Autowired
    private IYddUserService yddUserService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 登录接口
     *
     * @param yddUserLoginDTO
     * @return
     */
    @ApiOperation("登录接口")
    @PostMapping("/login")
    public Result login(@RequestBody YddUserLoginDTO yddUserLoginDTO) {
        //打印日志信息
        log.info("登录:{}", yddUserLoginDTO);
        YddUser user = yddUserService.login(yddUserLoginDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);
        //返回token
        Map<String, String> map = new HashMap<>();
        map.put("token", token);
        return Result.success(map);
    }
}
